/*
 * @Author: 郑子胜(Zechariahzheng)
 * @Date: 2024-01-25 11:32:10
 * @LastEditors: 郑子胜(Zechariahzheng)
 * @LastEditTime: 2024-01-25 15:02:41
 * @Descripttion: 
 */
#include "init.h"

char SN[19] = "";                                                   // SN码

// fs初始化
void ffsInit() 
{
  if (LittleFS.begin()) 
  {
    if (!(LittleFS.exists("/config.json"))) 
    {
      DEBUG_PRINTLN("config file not exist");
      //如果配置文件不存在，创建
      File configFile = LittleFS.open("/config.json", "w+");
      DynamicJsonDocument json(1024);
      json["sn"] = SN;
      String res;
      serializeJson(json, res);
      configFile.print(res);
      configFile.flush();
      configFile.close();
    }
    else
    {
      // 存在，则读取到全局变量
      File configFile = LittleFS.open("/config.json", "r");
      if (configFile)
      {
        DEBUG_PRINTLN("opened config file");
        DynamicJsonDocument json(1024);
        auto deserializeError = deserializeJson(json, configFile);
        if (!deserializeError)
        {
          DEBUG_PRINTLN("parsed json");
          if (json.containsKey("sn"))
            strlcpy(SN, json["sn"], sizeof(SN));
          configFile.close();
        }
        else
        {
          // 读取失败，重新写入默认值
          DEBUG_PRINTLN("failed to load json config, write again");
          configFile.close();
          configFile = LittleFS.open("/config.json", "w");
          DynamicJsonDocument json(1024);
          json["sn"] = SN;
          String res;
          serializeJson(json, res);
          configFile.print(res);
          configFile.flush();
          configFile.close();
        }
      }
    }
  }
  else 
  {
    DEBUG_PRINTLN("LittleFS mount failed");
    return;
  }
}

// wifi微信智能配网
void wifiManagerInit() 
{
  WxConfig wxConfig;
  wxConfig.init();
}